package netOcean;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * 字节流响应图片和以附件形式下载
 */
@WebServlet("/ServletDemo02")
public class ServletDemo02 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //固定写法
        resp.setContentType("application/octet-stream");
        //Content-Disposition意为指定，如何显示/处理附加的文件，以附件attachment，后面是下载后的文件名
        resp.setHeader("Content-Disposition", "attachment;filename=1.jpg");
        //获得真实路径
        String path = getServletContext().getRealPath("/WEB-INF/迪路兽.jpg");
        //建立输入流
        FileInputStream fileInputStream = new FileInputStream(new File(path));
        //创建响应对象的输出流
        ServletOutputStream outputStream = resp.getOutputStream();
        //具体传输逻辑
        byte[] buff = new byte[1024];
        int len;
        while ((len = fileInputStream.read(buff)) != -1) {
            outputStream.write(buff, 0, len);
        }
        fileInputStream.close();
        outputStream.close();

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
